package com.jingge.autojob.skeleton.model.task.remote;

import com.jingge.autojob.logging.model.producer.AutoJobLogHelper;
import com.jingge.autojob.skeleton.framework.task.AutoJobRunResult;
import com.jingge.autojob.skeleton.framework.task.AutoJobRunningContextHolder;
import com.jingge.autojob.skeleton.framework.task.AutoJobTask;
import com.jingge.autojob.skeleton.model.task.TaskExecutable;

/**
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-09-04 11:25
 * @email 1158055613@qq.com
 */
public class RemoteExecutable implements TaskExecutable {
    private transient final RemoteTask task;

    public RemoteExecutable(RemoteTask task) {
        this.task = task;
    }

    @Override
    public AutoJobTask getAutoJobTask() {
        return task;
    }

    @Override
    public boolean isExecutable() {
        return task.getInterceptor() != null;
    }

    @Override
    public Object execute(Object... params) throws Exception {
        AutoJobLogHelper logHelper = AutoJobLogHelper.getInstance();
        logHelper.info("开始请求，协议类型：{}，主机地址：{}:{}，请求类型：{}，建立连接超时：{}ms，读取超时：{}ms，写入超时：{}ms", task
                .getProtocolType()
                .getType(), task.getHost(), task.getPort(), task.getReqType(), task.getConnectTimeout(), task.getReadTimeout(), task.getWriteTimeout());
        long start = System.currentTimeMillis();
        RemoteTaskInterceptor interceptor = task.getInterceptor();
        if (interceptor == null) {
            throw new IllegalArgumentException("远程任务" + task.getReference() + "的任务拦截器为空");
        }
        RequestHandler requestHandler = interceptor.before(task);
        if (requestHandler == null) {
            throw new IllegalArgumentException("远程任务" + task.getReference() + "的请求处理器为空");
        }
        task.setRequestHandler(requestHandler);
        RemoteResponse remoteResponse = task
                .getRequestHandler()
                .handleRequest();
        AutoJobRunResult runResult = interceptor.after(task, remoteResponse);
        if (runResult != null && runResult.getResult() != null && runResult.getResult() instanceof String) {
            logHelper.info("请求完成，请求耗时：{}ms，响应长度：{}", System.currentTimeMillis() - start, ((String) runResult.getResult()).length());
        } else {
            logHelper.info("请求完成，请求耗时：{}ms", System.currentTimeMillis() - start);
        }
        return runResult;
    }

    @Override
    public Object[] getExecuteParams() {
        return new Object[]{};
    }
}
